//
//  Tools.m
//  MS3.0
//
//  Created by 徐杨 on 2017/6/15.
//  Copyright © 2017年 麦时. All rights reserved.
//

#import "Tools.h"
#import <CommonCrypto/CommonDigest.h>
#define TIME_ZONE @"Asia/Beijing"

#import "sys/utsname.h"
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

#include <ifaddrs.h>
#include <arpa/inet.h>
#include <netdb.h>
#import <dlfcn.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import "ToastTools.h"
#import <UMPush/UMessage.h>
#import "MeRegisterLoginVC.h"
//#import "MeRegisterVC.h"

//原始尺寸  ,放大图片方法
static CGRect oldframe;

@implementation Tools

+ (NSAttributedString *)RTFContentWithHTMLString:(NSString *)HTMLString contentWidth:(CGFloat)contentWidth {
    NSString *newString = [NSString stringWithFormat:@"<html>"
                           "<head>"
                           "</style>"
                           "<style>*{margin:3px 0px 3px 0px;padding:0 ;max-width:%f;}</style>"
                           "</head>"
                           "<body>%@</body>"
                           "</html>",contentWidth, HTMLString];
    NSData *data = [newString dataUsingEncoding:NSUnicodeStringEncoding];
    NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
    NSMutableAttributedString *htmlAttribute = [[NSMutableAttributedString alloc] initWithData:data                                        options:options                              documentAttributes:nil                                        error:nil];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    //设置文字的行间距
    [paragraphStyle setLineSpacing:10];
    [htmlAttribute addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [htmlAttribute length])];
    return htmlAttribute;
}
+ (CGSize)RTFContentSizeWithAttributed:(NSAttributedString *)attr contentWidth:(CGFloat)contentWidth {
    return [attr boundingRectWithSize:CGSizeMake(contentWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
}

+ (BOOL)isNewVersionWithKey:(NSString *)key {
    NSString *currentVersion = [[Tools getUserPhoneInfo] objectForKey:kAPP_VERSION];
    
    NSUserDefaults *defaults = kUSER_DEFAULTS;
    NSString *oldVersion = [defaults objectForKey:key];
    if ([currentVersion isEqualToString:oldVersion]) {
        return NO;
    }
    [defaults setObject:currentVersion forKey:key];
    [defaults synchronize];
    return YES;
}
#pragma mark - 获取components 对象
+ (NSDateComponents *)customComponents {
    
    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    unsigned unitOptions = NSCalendarUnitYear |
    NSCalendarUnitMonth |  NSCalendarUnitDay |
    NSCalendarUnitHour |  NSCalendarUnitMinute |
    NSCalendarUnitSecond | NSCalendarUnitWeekday;

    NSDateComponents *components = [calendar components:unitOptions fromDate:date];
    return components;
}

#pragma mark - 时间分割 (2017-10-30 09:58:23)
+ (NSString *)timeStrSegmentation:(NSString *)timeStr {
    // 根据空格截取
    NSArray *arr = [timeStr componentsSeparatedByString:@" "];
    if (arr.count >= 2) {
        return arr[0];
    } else {
        return nil;
    }
}

#pragma mark - 清理缓存
+ (void)cleanCache:(cleanCacheBlock)block {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
        
        if (!folderPath) {
            return;
        }
        //Caches路径
        NSString *cachePath = [NSString stringWithFormat:@"%@/Caches", folderPath];
        //判断caches路径是否存在
        NSFileManager *manager = [NSFileManager defaultManager];
        if (![manager fileExistsAtPath:cachePath]) {
            return;
        }
        
        //删除cache文件夹下的所有文件
        NSArray *dirArray = [manager contentsOfDirectoryAtPath:cachePath error:nil];
        
        for (NSString *subDir in dirArray) {
            //忽略user_db_name文件夹
            if (![subDir isEqualToString:@"user_db_name"]) {
                NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:[NSString stringWithFormat:@"%@/%@", cachePath, subDir]] objectEnumerator];
                //文件名
                NSString *fileName;
                while ((fileName = [childFilesEnumerator nextObject]) != nil) {
                    NSString *fileAbsolutePath = [[cachePath stringByAppendingPathComponent:subDir] stringByAppendingPathComponent:fileName];
                    [self deleteFileAtPath:fileAbsolutePath];
                }
            }
        }
        
        //删除Application Support文件夹下的所有文件
        NSString *supportPath = [NSString stringWithFormat:@"%@/Application Support", folderPath];
        //判断supportPath路径是否存在
        if (![manager fileExistsAtPath:supportPath]) {
            return;
        }
        
        //Application Support文件夹下的所有文件 user_db_name
        NSArray *supportDirArray = [manager contentsOfDirectoryAtPath:supportPath error:nil];
        
        for (NSString *supportDir in supportDirArray) {
            NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:[NSString stringWithFormat:@"%@/%@", supportPath, supportDir]] objectEnumerator];
            //文件名
            NSString *fileName;
            while ((fileName = [childFilesEnumerator nextObject]) != nil) {
                NSString *fileAbsolutePath = [[supportPath stringByAppendingPathComponent:supportDir] stringByAppendingPathComponent:fileName];
                [self deleteFileAtPath:fileAbsolutePath];
            }
        }
        
        //返回主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            block();
        });
    });
}

#pragma mark - 删除某个文件
+ (void)deleteFileAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath :filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    }
}

#pragma mark - 获取缓存文件大小
+ (CGFloat)cacheSize {
    NSString *folderPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    
    if (!folderPath) {
        return 0;
    }
    //Caches路径
    NSString *cachePath = [NSString stringWithFormat:@"%@/Caches", folderPath];
    //判断caches路径是否存在
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:cachePath]) {
        return 0;
    }
    
    //文件总大小
    long long folderSize = 0;
    
    //cache文件夹下的所有文件 user_db_name
    NSArray *cacheDirArray = [manager contentsOfDirectoryAtPath:cachePath error:nil];
    
    for (NSString *subDir in cacheDirArray) {
        //忽略用户文件夹
        if (![subDir isEqualToString:@"user_db_name"]) {
            NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:[NSString stringWithFormat:@"%@/%@", cachePath, subDir]] objectEnumerator];
            //文件名
            NSString *fileName;
            while ((fileName = [childFilesEnumerator nextObject]) != nil) {
                NSString *fileAbsolutePath = [[cachePath stringByAppendingPathComponent:subDir] stringByAppendingPathComponent:fileName];
                folderSize += [self fileSizeAtPath:fileAbsolutePath];
            }
        }
    }
    
    //Application Support文件夹下的所有文件
    NSString *supportPath = [NSString stringWithFormat:@"%@/Application Support", folderPath];
    //判断supportPath路径是否存在
    if (![manager fileExistsAtPath:supportPath]) {
        return folderSize;
    }
    
    //Application Support文件夹下的所有文件 user_db_name
    NSArray *supportDirArray = [manager contentsOfDirectoryAtPath:supportPath error:nil];
    
    for (NSString *supportDir in supportDirArray) {
        NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:[NSString stringWithFormat:@"%@/%@", supportPath, supportDir]] objectEnumerator];
        //文件名
        NSString *fileName;
        while ((fileName = [childFilesEnumerator nextObject]) != nil) {
            NSString *fileAbsolutePath = [[supportPath stringByAppendingPathComponent:supportDir] stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
    }
    
    return folderSize/(1024.0 * 1024.0);
}

#pragma mark - 获取单个文件大小
+ (long long)fileSizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath :filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    
    return 0;
}

#pragma mark - 格式化价格，带逗号
//+ (NSString *)priceWithSeparator:(NSNumber *)number {
//    if (!number) {
//        return @"";
//    }
//    NSString *resultString = [NSString strmethodComma:[NSString stringWithFormat:@"%.2f", [number doubleValue]]];
//    if (resultString.length > 0) {
//        return [NSString stringWithFormat:@"¥%@", resultString];
//    }
//    return @"";
//}

#pragma mark - 价格格式化 大于10000显示1万
+ (NSString *)priceFormat:(NSString *)priceString {
    NSInteger number = 0;
    if (![Tools isPureInt:priceString]) {
        return priceString;
    }
    else {
        number = [priceString integerValue];
    }

    if (number >= 10000) {
        return [NSString stringWithFormat:@"%.2f万", number/10000.0];
    }
    return priceString;
}

#pragma mark - 判断一个字符串是否是整形
+ (BOOL)isPureInt:(NSString*)string {
    if (!string) {
        return false;
    }
    //string不是浮点型
    if (![string containsString:@"."]) {
        NSScanner *scan = [NSScanner scannerWithString:string];
        int val;
        return[scan scanInt:&val] && [scan isAtEnd];
    }
    //string是浮点型
    else {
        NSArray *numberArray = [string componentsSeparatedByString:@"."];
        if (numberArray.count != 2) {
            return false;
        }
        else {
            NSString *behindNumber = numberArray[1];
            //如果小数点后的数字等于0，则是整数
            return ([behindNumber integerValue] == 0);
        }
    }
}
#pragma mark - 字符串插入逗号格式 是否加.00
+ (NSString *)priceFormatInsertComma:(NSString *)priceText isDecimals:(BOOL)isDecimals{
    if (priceText.length == 0 || !priceText) {
        return nil;
    }
    NSString *replaceStr = priceText;
    NSString *decimalPointStr = @"";
    if ([priceText containsString:@"."]) {
            // 价格包含点. 则截取点后面的小数临时保存, 转换完成后拼接返回
            replaceStr = [priceText substringToIndex:[priceText length] - 3];
            decimalPointStr = [priceText substringFromIndex:[priceText length] - 3];
    }
    NSString *str = [replaceStr substringWithRange:NSMakeRange(replaceStr.length % 3, replaceStr.length - replaceStr.length % 3)];
    NSString *strs = [replaceStr substringWithRange:NSMakeRange(0, replaceStr.length % 3)];
    for (NSInteger i = 0; i < str.length; i = i + 3) {
        NSString *sss = [str substringWithRange:NSMakeRange(i, 3)];
        strs = [strs stringByAppendingString:[NSString stringWithFormat:@",%@",sss]];
    }
    if ([[strs substringWithRange:NSMakeRange(0, 1)] isEqualToString:@","]) {
        strs = [strs substringWithRange:NSMakeRange(1, strs.length - 1)];
    }

    return [[NSString stringWithFormat:@"%@",strs] stringByAppendingString:decimalPointStr];
    
}


#pragma mark - 模型转字典
+ (NSMutableDictionary *)returnDictionaryByModel:(NSObject *)model {
    NSMutableDictionary *userDic = [NSMutableDictionary dictionary];
    unsigned int count = 0;
    objc_property_t *properties = class_copyPropertyList([model class], &count);
    for (int i = 0; i < count; i++) {
        const char *name = property_getName(properties[i]);
        
        NSString *propertyName = [NSString stringWithUTF8String:name];
        id propertyValue = [model valueForKey:propertyName];
        if (propertyValue) {
            [userDic setObject:propertyValue forKey:propertyName];
        }
        
    }
    free(properties);
    return userDic;
}

#pragma mark - 根据image 获得image的type jpg/png
+ (NSString *)contentTypeWithImage:(UIImage *)image {
    
    NSData *imageData = UIImagePNGRepresentation(image);
    uint8_t c;
    [imageData getBytes:&c length:1];
    switch (c) {
        case 0xFF: return @"jpeg";
            
        case 0x89: return @"png";
            
        case 0x47: return @"gif";
            
        case 0x49:
        case 0x4D: return @"tiff";
            
        case 0x52:
            
            if ([imageData length] < 12) {
                return nil;
            }
            
            NSString *testString = [[NSString alloc] initWithData:[imageData subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                
                return @"webp";
            }
            return nil;
    }
    return nil;
}

#pragma mark - 相机权限
+ (BOOL)devicePermissionForCamera {
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        NSLog(@"相机不能用");
        return NO;
    }

    //判断是否已授权
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == ALAuthorizationStatusDenied||authStatus == ALAuthorizationStatusRestricted) {
        
        [ToastTools showDialogWithTitle:@"相机没有权限" content:@"请到设置-隐私-相机中开启" submitAction:^{
            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }
            
//            if (kApplicationCanOpenURL(identifier)) {
//                kApplicationOpenURL(identifier);
//            }
        }];

        return NO;
    }

    return YES;
}
#pragma mark - 相册权限
+ (BOOL)devicePermissionForPhotoAlbum {
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        return NO;
    }
    return YES;
}

#pragma mark - 判断是否含有非法字符
+ (BOOL)judgeTheillegalCharacter:(NSString *)content {
    //提示 标签不能输入特殊字符
    NSString *str = @"^[A-Za-z0-9\\u4e00-\u9fa5]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", str];
    if (![emailTest evaluateWithObject:content]) {
        return YES;
    }
    return NO;
}

#pragma mark - 检测字符串是否是纯数字
+ (BOOL)isNumber:(NSString *)num {
    NSString *number = @"0123456789";
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:number] invertedSet];
    NSString *filtered = [[num componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [num isEqualToString:filtered];
}

+ (NSString *)currentVCNameWithClass:(Class)aClass {
    if (aClass) {
        return NSStringFromClass([aClass class]);
    }
    return nil;
}

#pragma mark - 检测字符串是否是数字或字母组成
+ (BOOL)isNumberOrLetter:(NSString *)num {
    NSString *numberOrLetter = @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:numberOrLetter] invertedSet];
    NSString *filtered = [[num componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return [num isEqualToString:filtered];
}


#pragma mark - 只能输入中文,英文,数字 正则
+ (BOOL)judgeRegexOnlyChineseEnglishNumber:(NSString *)content {
    NSString *regex = @"[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![pred evaluateWithObject:content]) {
        return YES;
    }
    return NO;
}
#pragma mark - 判断长度大于8位 是否同时包含数字和字符
+ (BOOL)judgePassWordLegal:(NSString *)content {
    BOOL result = false;
    if ([content length] >= 8){
        // 判断长度大于8位后再接着判断是否同时包含数字和字符
        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:content];
    }
    return result;
}


//+ (BOOL)judgeRegexOnlyEnglishNumber:(NSString *)content {
//    NSString *regex = @"^[A-Za-z0-9]+$";
//    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
//    if (![pred evaluateWithObject:content]) {
//        return YES;
//    }
//    return NO;
//}
#pragma mark - 是否包含emoji表情
+ (BOOL)stringContainsEmoji:(NSString *)string {
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar high = [substring characterAtIndex: 0];
                                
                                // Surrogate pair (U+1D000-1F9FF)
                                if (0xD800 <= high && high <= 0xDBFF) {
                                    const unichar low = [substring characterAtIndex: 1];
                                    const int codepoint = ((high - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000;
                                    
                                    if (0x1D000 <= codepoint && codepoint <= 0x1F9FF){
                                        returnValue = YES;
                                    }
                                    
                                    // Not surrogate pair (U+2100-27BF)
                                } else {
                                    if (0x2100 <= high && high <= 0x27BF){
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}

#pragma mark - 获取缓存内存大小
//+ (CGFloat)getCachSize {
//
//    NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];
//    //获取自定义缓存大小
//    //用枚举器遍历 一个文件夹的内容
//    //1.获取 文件夹枚举器
//    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
//    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
//    __block NSUInteger count = 0;
//    //2.遍历
//    for (NSString *fileName in enumerator) {
//        NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
//        NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
//        count += fileDict.fileSize;//自定义所有缓存大小
//    }
//    // 得到是字节  转化为M
//    CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
//    return totalSize;
//}

#pragma mark - 清除缓存
//+ (void)clearMemeory {
//    //删除两部分
//    //1.删除 sd 图片缓存
//    //先清除内存中的图片缓存
//    [[SDImageCache sharedImageCache] clearMemory];
//    //清除磁盘的缓存
//    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
//
//    }];
//    //2.删除自己缓存
//    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
//    [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
//}

#pragma mark - 获取视频任意帧图片
+ (UIImage *)thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode =AVAssetImageGeneratorApertureModeEncodedPixels;
    
    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];
    
    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);
    
    UIImage *thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage:thumbnailImageRef] : nil;
    return thumbnailImage;
}

#pragma mark - 计算文字大小
+ (CGSize)sizeForText:(NSString *)text fontSize:(CGFloat)fontSize size:(CGSize)size {
    if (text && text.length > 0) {
        return [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]} context:nil].size;
    }else {
        return CGSizeZero;
    }
}

+ (CGSize)boundingAllRectWithSize:(NSString*)txt font:(UIFont*)font size:(CGSize)size {
    return [txt boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: font} context:nil].size;
}




//MD5加密
+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (int)str.length, digest);
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [result appendFormat:@"%02x", digest[i]];
    return result;
}

#pragma mark - 将字符串转化成控制器
+ (UIViewController *)StringIntoViewController:(NSString *)classString
{
    UIViewController *vc = [NSClassFromString(classString) new];
    return vc;
}

#pragma mark - 验证银行卡号是否规范
+ (BOOL)validateBankCardWithNumber:(NSString *)cardNum
{
    NSString * CT = @"^([0-9]{16}|[0-9]{19})$";
    NSPredicate *regextestCard = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if ([regextestCard evaluateWithObject:cardNum] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark - 验证正整数
+ (BOOL)validatePositiveInteger:(NSString *)integer {
    NSString *regex = @"^[0-9]*$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    return [emailTest evaluateWithObject:integer];
}

#pragma mark - 判断身份证号码是否规范
+ (BOOL)checkIdentityCardNo:(NSString*)cardNo
{
    if (cardNo.length != 18) {
        return  NO;
    }
    NSArray* codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil]  forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];
    
    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];
    
    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
        return NO;
    }
    int sumValue = 0;
    
    for (int i =0; i<17; i++) {
        sumValue+=[[cardNo substringWithRange:NSMakeRange(i , 1) ] intValue]* [[codeArray objectAtIndex:i] intValue];
    }
    
    NSString* strlast = [checkCodeDic objectForKey:[NSString stringWithFormat:@"%d",sumValue%11]];
    
    if ([strlast isEqualToString: [[cardNo substringWithRange:NSMakeRange(17, 1)]uppercaseString]]) {
        return YES;
    }
    return  NO;
}

#pragma mark - 验证手机号码
+ (BOOL)validatePhone:(NSString *)mobileNum
{
    if (mobileNum.length != 11)
    {
        return NO;
    }
    /**
     * 手机号码:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9]
     * 移动号段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     * 联通号段: 130,131,132,155,156,185,186,145,176,1709
     * 电信号段: 133,153,180,181,189,177,1700
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705
     */
    NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\\d{8}$)|(^1705\\d{7}$)";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186,145,176,1709
     */
    NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\\d{8}$)|(^1709\\d{7}$)";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177,1700
     */
    NSString *CT = @"(^1(33|53|77|8[019])\\d{8}$)|(^1700\\d{7}$)";
    /**
     25     * 大陆地区固话及小灵通
     26     * 区号：010,020,021,022,023,024,025,027,028,029
     27     * 号码：七位或八位
     28     */
    //  NSString * PHS = @"^(0[0-9]{2})\\d{8}$|^(0[0-9]{3}(\\d{7,8}))$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }else {
        return NO;
    }
}

#pragma mark - 拨打电话
+ (void)makePhoneCallWithTelNumber:(NSString *)tel
{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",tel]]];
}

#pragma mark - 直接打开网页
+ (void)openURLWithUrlString:(NSString *)url
{
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",url]]]) {
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",url]]];
    }
}

#pragma mark - 获取当前时间
+ (NSString *)currentTime {
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    NSDate *curDate = [NSDate date];//获取当前日期
    [formater setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//这里去掉 具体时间 保留日期
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:TIME_ZONE];
    [formater setTimeZone:timeZone];
    NSString *curTime = [formater stringFromDate:curDate];
    
    return curTime;
}

#pragma mark - 将时间转换成时间戳
/**
 *  时间戳：指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数。
 */
+ (NSString *)timeStringIntoTimeStamp:(NSString *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:TIME_ZONE];
    [dateFormatter setTimeZone:timeZone];
    
    NSDate *date = [dateFormatter dateFromString:time];
    
    NSString *timeSP = [NSString stringWithFormat:@"%ld",(long)[date timeIntervalSince1970]];
    
    return timeSP;
}

#pragma mark - 将时间戳转换成时间
+ (NSString *)timeStampIntoTimeString:(NSString *)time
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    /* 设置时区 */
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:TIME_ZONE];
    [dateFormatter setTimeZone:timeZone];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[time intValue]];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    //dateString = [dateString substringToIndex:20];
    return  dateString;
}

#pragma mark - 将时间戳转换成年月日
+ (NSString *)timeStampIntoYYMMDD:(NSTimeInterval)time {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    /* 设置时区 */
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:TIME_ZONE];
    [dateFormatter setTimeZone:timeZone];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
    
    NSString *dateString = [dateFormatter stringFromDate:date];
    //dateString = [dateString substringToIndex:20];
    return  dateString;
}

#pragma mark - 通过时间字符串获取年、月、日
+ (NSArray *)getYearAndMonthAndDayFromTimeString:(NSString *)time
{
    NSString *year = [time substringToIndex:4];
    NSString *month = [[time substringFromIndex:5] substringToIndex:2];
    NSString *day = [[time substringFromIndex:8] substringToIndex:2];
    
    return @[year,month,day];
}
#pragma mark - 获取今天、明天、后天的日期
+ (NSArray *)timeForTheRecentDate
{
    NSMutableArray *dateArr = [[NSMutableArray alloc]init];
    
    //今天
    NSDateFormatter *formater = [[ NSDateFormatter alloc] init];
    NSDate *curDate = [NSDate date];//获取当前日期
    [formater setDateFormat:@"YYYY-MM-dd HH:mm:ss"];//这里去掉 具体时间 保留日期
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:TIME_ZONE];
    [formater setTimeZone:timeZone];
    NSString * curTime = [formater stringFromDate:curDate];
    
    NSArray *today = [self getYearAndMonthAndDayFromTimeString:curTime];
    [dateArr addObject:today];
    
    
    //明天
    NSString *timeStamp = [self timeStringIntoTimeStamp:curTime];
    NSInteger seconds = 24*60*60 + [timeStamp integerValue];
    timeStamp = [NSString stringWithFormat:@"%ld",(long)seconds];
    curTime = [self timeStampIntoTimeString:timeStamp];
    
    NSArray *tomorrow = [self getYearAndMonthAndDayFromTimeString:curTime];
    [dateArr addObject:tomorrow];
    
    return [NSArray arrayWithArray:dateArr];
}

#pragma mark - 获取当前时间的时间戳
+ (NSString *)getCurrentTimestamp {
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval time = [date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%0.f", time];//转为字符型
    return timeString;
}

#pragma mark - 当前界面截图
+ (UIImage *)imageFromCurrentView:(UIView *)view
{
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, view.layer.contentsScale);
    
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return image;
}

#pragma mark - 获取Documents中文件的路径
+ (NSString *)accessToTheDocumentsInTheFilePath:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    
    return filePath;
}

#pragma mark - 判断网址是否有效
+ (BOOL)validateHttp:(NSString *)textString
{
    NSString* number=@"^([w-]+.)+[w-]+(/[w-./?%&=]*)?$";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}

#pragma mark - 给view设置边框
+ (void)setBorderWithView:(UIView *)view top:(BOOL)top left:(BOOL)left bottom:(BOOL)bottom right:(BOOL)right borderColor:(UIColor *)color borderWidth:(CGFloat)width
{
    if (top) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, view.frame.size.width, width);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (left) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, 0, width, view.frame.size.height);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (bottom) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(0, view.frame.size.height - width, view.frame.size.width, width);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
    if (right) {
        CALayer *layer = [CALayer layer];
        layer.frame = CGRectMake(view.frame.size.width - width, 0, width, view.frame.size.height);
        layer.backgroundColor = color.CGColor;
        [view.layer addSublayer:layer];
    }
}

#pragma mark - 给view设置圆角
/**
 *  给view设置圆角(指定圆角)
 *
 */
+ (void)setCornerRadiuswithView:(UIView *)view targetAngles:(UIRectCorner) targetAngles cornerRadii:(CGSize) size {
    
    
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:targetAngles cornerRadii:size];
    
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = view.bounds;
    maskLayer.path = maskPath.CGPath;
    view.layer.mask = maskLayer;
}

#pragma mark - 将数组中重复的对象去除，只保留一个
+ (NSMutableArray *)arrayWithMemberIsOnly:(NSMutableArray *)array
{
    NSMutableArray *categoryArray =  [[NSMutableArray alloc] init];
    for (unsigned i = 0; i < [array count]; i++) {
        @autoreleasepool {
            if ([categoryArray containsObject:[array objectAtIndex:i]] == NO) {
                [categoryArray addObject:[array objectAtIndex:i]];
            }
        }
    }
    return categoryArray;
}

#pragma mark - 图片大小设置
+ (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size
{
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // the size of CGContextRef
    int w = size.width;
    int h = size.height;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 44 * w, colorSpace,kCGImageAlphaPremultipliedFirst);
    CGRect rect = CGRectMake(0, 0, w, h);
    
    CGContextBeginPath(context);
    addRoundedRectToPath(context, rect, size.width/3, size.height/3);
    CGContextClosePath(context);
    CGContextClip(context);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), scaledImage.CGImage);
    //CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    //返回新的改变大小后的图片
    return scaledImage;
}

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,
                                 float ovalHeight)
{
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }
    
    CGContextSaveGState(context);
    CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM(context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth(rect) / ovalWidth;
    fh = CGRectGetHeight(rect) / ovalHeight;
    
    CGContextMoveToPoint(context, fw, fh/2);  // Start at lower right corner
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);  // Top right corner
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right
    
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

#pragma mark - 获取当前屏幕显示的viewcontroller
+ (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

#pragma mark - 获取当前处于activity状态的view controller
+ (UIViewController *)activityViewController
{
    UIViewController* activityViewController = nil;
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if(window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow *tmpWin in windows)
        {
            if(tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    NSArray *viewsArray = [window subviews];
    if([viewsArray count] > 0)
    {
        UIView *frontView = [viewsArray objectAtIndex:0];
        
        id nextResponder = [frontView nextResponder];
        
        if([nextResponder isKindOfClass:[UIViewController class]])
        {
            activityViewController = nextResponder;
        }
        else
        {
            activityViewController = window.rootViewController;
        }
    }
    
    return activityViewController;
}

#pragma mark - 清空字典数据
+ (NSMutableDictionary *)clearNullData:(NSDictionary *)dic
{
    NSMutableDictionary *result = [NSMutableDictionary new];
    
    NSArray *data = dic.allKeys;
    for (int i=0; i<data.count; i++) {
        
        NSString *str = dic[data[i]];
        
        if ((NSNull *)str == [NSNull null]){
            [result setObject:@"" forKey:data[i]];
        }else{
            [result setObject:dic[data[i]] forKey:data[i]];
        }
    }
    
    return result;
}

#pragma mark - 格式化千分位
+ (NSString *)positiveFormat:(NSString *)text
{
    if(!text || [text floatValue] == 0)
    {
        return @"0.00";
    }
    else if ([text floatValue]<1)
    {
        return [NSString stringWithFormat:@"%@",text];
    }
    else
    {
        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setPositiveFormat:@",###.00"];
        return [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[text doubleValue]]];
    }
    return @"";
}

#pragma mark - 不四舍五入  小数
+ (NSString *)notRounding:(float)price afterPoint:(int)position {
    NSDecimalNumberHandler* roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundDown scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    
    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    
    return [NSString stringWithFormat:@"%0.2f元",[roundedOunces floatValue]];
}

#pragma mark - 获取用户手机信息
+ (NSMutableDictionary *)getUserPhoneInfo {
    NSMutableDictionary *phoneInfoDict = [NSMutableDictionary new];
    
    //手机系统版本
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // 当前应用软件版本  比如：1.0.1
    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    //手机序列号（设备号）
    NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString];
    
    //手机品牌型号
    [phoneInfoDict setObject:[self getUserPhoneModelNumber] forKey:@"mobiletype"];
    
    //添加手机系统版本
    [phoneInfoDict setObject:phoneVersion forKey:@"sysversion"];
    
    //登录来源 PC IOS Android WeChat
    [phoneInfoDict setObject:@"IOS" forKey:@"logintype"];
    
    //添加应用app版本号
    [phoneInfoDict setObject:appCurVersion forKey:kAPP_VERSION];
    
    //添加手机序列号（设备号）
    [phoneInfoDict setObject:identifierNumber forKey:@"devicenumber"];
    return phoneInfoDict;
}

#pragma mark - 获取手机品牌型号
+ (NSString *)getUserPhoneModelNumber
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    return deviceString;
}

#pragma mark - 判断手机型号是否是5s以上
+ (BOOL)judgePhoneTypeIsCanFingerprint
{
    
    //获取手机品牌型号
    NSRange range = {6,1};
    
    NSString *phoneModelNum = @"0";
    if ([self getUserPhoneModelNumber].length >= 7)
    {
        phoneModelNum = [[self getUserPhoneModelNumber] substringWithRange:range];
    }
    
    if ([phoneModelNum integerValue] > 5)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

#pragma mark - 从单例类（NSUserDefaults）中取出可变数组（用于后面操作添加或者删除元素）
+ (NSMutableArray *)getMutableArrayFromNSUserDefaults:(NSString *)path
{
    NSMutableArray *Array = [NSMutableArray new];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //mutableCopy 一定要添加 否则在对数组进行添加或者删除元素等操作的时候线程会卡死
    Array = [[defaults objectForKey:path] mutableCopy];
    
    return Array;
}

#pragma mark - 字典转化成字符串
+ (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}
#pragma mark - 获取设备IP地址
+ (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0)
    {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL)
        {
            if(temp_addr->ifa_addr->sa_family == AF_INET)
            {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
                {                     // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }     // Free memory
    freeifaddrs(interfaces);
    return address;
}

#pragma mark - 获取host属性
+ (NSString *)hostname
{
    /*
     char baseHostName[256]; // Thanks, Gunnar Larisch
     int success = gethostname(baseHostName, 255);
     if (success != 0) return nil;
     baseHostName[255] = '/0';
     
     #if TARGET_IPHONE_SIMULATOR
     return [NSString stringWithFormat:@"%s", baseHostName];
     #else
     return [NSString stringWithFormat:@"%s.local", baseHostName];
     #endif
     */
    return @"";
}

#pragma mark - 获取本地host(主机)的IP地址
+ (NSString *)localIPAddress
{
    struct hostent *host = gethostbyname([[self hostname] UTF8String]);
    if (!host) {herror("resolv"); return nil;}
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}

#pragma mark - 获取设备的Mac地址
+ (NSString *)macAddress
{
    int mib[6];
    size_t len;
    char *buf;
    unsigned char *ptr;
    struct if_msghdr *ifm;
    struct sockaddr_dl *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return NULL;
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return NULL;
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return NULL;
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    // NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    
    NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    return [outstring uppercaseString];
}

#pragma mark -   图片转成base64编码
+ (NSString *)imageConvertFormatBase64imageName:(NSString *)imageName {
    UIImage *originImage = [UIImage imageNamed:imageName];
    
    NSData *data = UIImageJPEGRepresentation(originImage, 1.0f);
    
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

#pragma mark - 将数组里的字符串排序
+ (NSMutableArray *)Transformation:(NSArray *)dataArray isGrouping:(BOOL)grouping
{
    NSMutableArray *TwoArr = [NSMutableArray array];
    for (NSString *TransformationStr in dataArray)
    {
        NSMutableString *pinyin = [TransformationStr mutableCopy];
        CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
        CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
        [TwoArr addObject:pinyin];
    }
    NSMutableArray *ThreeArr = [NSMutableArray array];
    for (__strong NSString *ScreenStr in TwoArr)
    {
        ScreenStr = [ScreenStr substringToIndex:1];
        if (ThreeArr.count == 0)
        {
            [ThreeArr addObject:ScreenStr];
        }
        else
        {
            BOOL bl = [ThreeArr containsObject:ScreenStr];
            if (!bl)
            {
                [ThreeArr addObject:ScreenStr];
            }
        }
    }
    NSArray *FourArr = [ThreeArr sortedArrayUsingSelector:@selector(compare:)];
    NSMutableArray *MyArr = [NSMutableArray array];
    NSMutableArray *allNewDataArr = [NSMutableArray array];
    for (NSString *str in FourArr)
    {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:str forKey:@"title"];  // 索引
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < TwoArr.count; i++)
        {
            NSString *missstr = TwoArr[i];
            missstr = [missstr substringToIndex:1];
            if ([str isEqualToString:missstr])
            {
                [arr addObject:dataArray[i]];
            }
        }
        [dic setObject:arr forKey:@"info"];
        for (id obj in arr) {
            [allNewDataArr addObject:obj];
        }
        
        [MyArr addObject:dic];
        
    }
    return grouping ? MyArr : allNewDataArr;
}

#pragma mark -  获取rootViewController
+ (UIViewController *)rootViewController {
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    return window.rootViewController;
}

#pragma mark - 获取Window当前显示的ViewController
+ (UIViewController*)currentViewController {
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1) {
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
        
    }
    
    return vc;
}
+ (CGFloat)heightForImage:(UIImage *)image targetWidth:(NSInteger) defineWidth

{
    CGSize size = image.size;
    
    CGFloat scale = defineWidth / size.width;
    
    CGFloat imageH = size.height * scale;
    
    return imageH;
    
}

/**
 *  检测麦克风权限，仅支持iOS7.0以上系统
 *
 *  @return 准许返回YES;否则返回NO
 */
//+ (BOOL)isMicrophonePermissionGranted {
//    if ([[AVAudioSession sharedInstance] respondsToSelector:@selector(requestRecordPermission:)]) {
//        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//        __block BOOL isGranted=YES;
//        [[AVAudioSession sharedInstance] performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
//            isGranted=granted;
//            dispatch_semaphore_signal(sema);
//        }];
//        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//        return isGranted;
//    }
//    else{
//        return YES;
//    }
//}

/**
 *  检测相机权限
 *
 *  @return 准许返回YES;否则返回NO
 */
+ (BOOL)isCapturePermissionGranted {
    if([AVCaptureDevice respondsToSelector:@selector(authorizationStatusForMediaType:)]){
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if(authStatus ==AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied){
            return NO;
        }
        else if(authStatus==AVAuthorizationStatusNotDetermined){
            dispatch_semaphore_t sema = dispatch_semaphore_create(0);
            __block BOOL isGranted=YES;
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                isGranted=granted;
                dispatch_semaphore_signal(sema);
            }];
            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
            return isGranted;
        }
        else{
            return YES;
        }
    }
    else{
        return YES;
    }
}

///**
// *  检测相册权限
// *
// *  @return 准许返回YES;否则返回NO
// */
//+ (BOOL)isAssetsLibraryPermissionGranted {
//    if([ALAssetsLibrary respondsToSelector:@selector(authorizationStatus)]){
//        ALAuthorizationStatus authStatus = [ALAssetsLibrary authorizationStatus];
//        if (authStatus == ALAuthorizationStatusRestricted || authStatus ==ALAuthorizationStatusDenied){
//            return NO;
//        }
//        else if( authStatus== ALAuthorizationStatusNotDetermined){
//            dispatch_semaphore_t sema = dispatch_semaphore_create(0);
//            __block BOOL isGranted=YES;
//            
//            dispatch_queue_t dispatchQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//            dispatch_async(dispatchQueue, ^(void) {
//                ALAssetsLibrary * assetsLibrary=[[ALAssetsLibrary alloc] init];
//                [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
//                    isGranted=YES;
//                    *stop = YES;
//                    NSLog(@"enumerate");
//                    dispatch_semaphore_signal(sema);
//                } failureBlock:^(NSError *error) {
//                    isGranted=NO;
//                    NSLog(@"error:%ld %@",(long)error.code,error.description);
//                    dispatch_semaphore_signal(sema);
//                }];
//            });
//            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
//            return isGranted;
//        }
//        else{
//            return YES;
//        }
//    }else{
//        return YES;
//    }
//}


/**
 *  浏览大图
 *
 *  @param currentImageview 图片所在的imageView
 */
+ (void)scanBigImageWithImageView:(UIImageView *)currentImageview {
    
    //当前imageview的图片
    UIImage *image = currentImageview.image;
    //当前视图
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    //背景
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    //当前imageview的原始尺寸->将像素currentImageview.bounds由currentImageview.bounds所在视图转换到目标视图window中，返回在目标视图window中的像素值
    oldframe = [currentImageview convertRect:currentImageview.bounds toView:window];
    [backgroundView setBackgroundColor:[UIColor colorWithRed:107/255.0 green:107/255.0 blue:99/255.0 alpha:0.6]];
    //此时视图不会显示
    [backgroundView setAlpha:0];
    //将所展示的imageView重新绘制在Window中
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:oldframe];
    [imageView setImage:image];
    [imageView setTag:1024];
    [backgroundView addSubview:imageView];
    //将原始视图添加到背景视图中
    [window addSubview:backgroundView];
    
    
    //添加点击事件同样是类方法 -> 作用是再次点击回到初始大小
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideImageView:)];
    [backgroundView addGestureRecognizer:tapGestureRecognizer];
    
    //动画放大所展示的ImageView
    
    [UIView animateWithDuration:0.4 animations:^{
        CGFloat y,width,height;
        y = ([UIScreen mainScreen].bounds.size.height - image.size.height * [UIScreen mainScreen].bounds.size.width / image.size.width) * 0.5;
        //宽度为屏幕宽度
        width = [UIScreen mainScreen].bounds.size.width;
        //高度 根据图片宽高比设置
        height = image.size.height * [UIScreen mainScreen].bounds.size.width / image.size.width;
        [imageView setFrame:CGRectMake(0, y, width, height)];
        //重要！ 将视图显示出来
        [backgroundView setAlpha:1];
    } completion:^(BOOL finished) {
        
    }];
    
}

/**
 *  恢复imageView原始尺寸
 *
 *  @param tap 点击事件
 */
+ (void)hideImageView:(UITapGestureRecognizer *)tap {
    UIView *backgroundView = tap.view;
    //原始imageview
    UIImageView *imageView = [tap.view viewWithTag:1024];
    //恢复
    [UIView animateWithDuration:0.4 animations:^{
        [imageView setFrame:oldframe];
        [backgroundView setAlpha:0];
    } completion:^(BOOL finished) {
        //完成后操作->将背景视图删掉
        [backgroundView removeFromSuperview];
    }];
}



+(void)pushSinge{
    //    @weakify(self);
    
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle:@"取消" style:QMUIAlertActionStyleCancel handler:NULL];
    
    
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle:@"登陆" style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController *aAlertController, QMUIAlertAction *action) {
        //        @strongify(self);
        [self pushMeRegisterVC];
     
        
    }];
    
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"未登录" message:@"请先去登陆" preferredStyle:QMUIAlertControllerStyleAlert];
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController showWithAnimated:YES];
    
    
    //移除别名
    [UMessage removeAlias:kUSER_INFO_MANAGER.userId type:@"userId" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        NSLog(@"");
    }];
                [kUSER_INFO_MANAGER saveCookie];
    [kUSER_INFO_MANAGER removeUserInfo];
    [kUSER_INFO_MANAGER cleanCookie];
    kUSER_INFO_MANAGER.getMyEnquiryList = NO;
    kUSER_INFO_MANAGER.getFollowGoods = NO;    
}

+(void)pushMeRegisterVC{
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [Tools getCurrentVCFrom:rootViewController];
    
    [currentVC.navigationController pushViewController:[[MeRegisterLoginVC alloc]init] animated:YES];
}

- (void)push:(NSDictionary *)params
{
    // 类名
    NSString *class = @"MeRegisterVC";
    const char *className = [class cStringUsingEncoding:NSASCIIStringEncoding];
    
    // 从一个字串返回一个类
    Class newClass = objc_getClass(className);
    if (!newClass)
    {
        // 创建一个类
        Class superClass = [NSObject class];
        newClass = objc_allocateClassPair(superClass, className, 0);
        // 注册你创建的这个类
        objc_registerClassPair(newClass);
    }
    // 创建对象
    id instance = [[newClass alloc] init];
    
//    // 对该对象赋值属性
//    NSDictionary * propertys = params[@"property"];
//    [propertys enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
//        // 检测这个对象是否存在该属性
//        if ([self checkIsExistPropertyWithInstance:instance verifyPropertyName:key]) {
//            // 利用kvc赋值
//            [instance setValue:obj forKey:key];
//        }
//    }];
//
    // 获取导航控制器
    UITabBarController *tabVC = (UITabBarController*)[UIApplication sharedApplication].keyWindow.rootViewController;

//    UITabBarController *tabVC = (UITabBarController *)self.window.rootViewController;
    UINavigationController *pushClassStance = (UINavigationController *)tabVC.viewControllers[tabVC.selectedIndex];
    // 跳转到对应的控制器
    [pushClassStance pushViewController:instance animated:YES];
}



+(UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [Tools getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [Tools getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}



+(void)showTips:(NSString *)str {
    
    if (str.length ==0 || str == nil) {
        return;
    }
    
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    UIViewController *currentVC = [Tools getCurrentVCFrom:rootViewController];
    
    QMUITips *tips = [QMUITips createTipsToView:
                      currentVC.view];
    tips.toastPosition = QMUIToastViewPositionBottom;
    QDCustomToastAnimator *customAnimator = [[QDCustomToastAnimator alloc] initWithToastView:tips];
    tips.toastAnimator = customAnimator;
    QDCustomToastContentView *customContentView = [[QDCustomToastContentView alloc] init];
    [customContentView renderWithText:str];
    tips.contentView = customContentView;
    [tips showAnimated:YES];
    [tips hideAnimated:YES afterDelay:1];
}




@end
